package io.polly.common.util;

import io.polly.common.constant.QueueTypeEnum;
import io.polly.common.constant.RejectedTypeEnum;

import java.util.concurrent.*;

/**
 * @author ldz
 * @version V1.0
 * @title: DynamicExecutorUtil
 * @description: 便于后续扩展新的BlockingQueue及RejectedExecutionHandle
 * @date: 2022/3/21 17:40
 */

public class DynamicExecutorUtil {

    public static BlockingQueue<Runnable> buildBlockingQueue(String queueName, int capacity, boolean fair) {

        QueueTypeEnum queueTypeEnum = QueueTypeEnum.valueOf(queueName);
        switch(queueTypeEnum) {
            case ARRAY_BLOCKING_QUEUE:
                return new ArrayBlockingQueue<>(capacity);
            case SYNCHRONOUS_QUEUE:
                return new SynchronousQueue<>(fair);
            case LINKED_BLOCKING_QUEUE:
                return new LinkedBlockingQueue<>(capacity);
            case PRIORITY_BLOCKING_QUEUE:
                return new PriorityBlockingQueue<>(capacity);
            default:
                return new LinkedBlockingQueue<>(capacity);
        }
    }

    public static RejectedExecutionHandler buildRejectedHandler(String rejectedName){

        RejectedTypeEnum rejectedTypeEnum = RejectedTypeEnum.valueOf(rejectedName);
        switch(rejectedTypeEnum) {
            case ABORT_POLICY:
                return new ThreadPoolExecutor.AbortPolicy();
            case DISCARD_POLICY:
                return new ThreadPoolExecutor.DiscardPolicy();
            case CALLER_RUNS_POLICY:
                return new ThreadPoolExecutor.CallerRunsPolicy();
            case DISCARD_OLDEST_POLICY:
                return new ThreadPoolExecutor.DiscardOldestPolicy();
            default:
                return new ThreadPoolExecutor.AbortPolicy();
        }

    }
}
